package com.microcm.system.entity;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.microcm.common.CUtils;

/**
 * 索引查询单元
 * 
 * @author kansum
 */
public class IndexSearcherUnit
{
	private boolean searchReady;

	private String indexRoot;

	private Directory directory;

	private IndexReader reader;

	private IndexSearcher indexSearcher;

	/**
	 * 初始化索引查询器
	 * 
	 * @param indexRootDir
	 * @throws IOException
	 */
	public IndexSearcherUnit(String indexRoot)
	{
		this.indexRoot = indexRoot;
	}

	/**
	 * 打开索引查询器
	 * 
	 * @author kansum
	 */
	public boolean openIndexSearcher() throws IOException
	{
		File idxDir = new File(indexRoot);
		if (!idxDir.exists() || CUtils.isEmpty(idxDir.list()))
		{
			this.searchReady = false;
		}
		else
		{
			this.directory = FSDirectory.open(idxDir);
			this.reader = IndexReader.open(this.directory, true);
			this.indexSearcher = new IndexSearcher(reader);
			this.searchReady = true;
		}
		return this.searchReady;
	}

	public boolean isSearchReady()
	{
		return searchReady;
	}

	/**
	 * 获得索引搜索器
	 * 
	 * @author kansum
	 */
	public synchronized IndexSearcher getIndexSearcher()
	{
		if (this.searchReady)
			return this.indexSearcher;
		else
			return null;
	}

	/**
	 * 关闭索引查询器
	 * 
	 * @author kansum
	 */
	public synchronized void closeIndexSearcher() throws IOException
	{
		this.indexSearcher.close();
		this.reader.close();
		this.directory.close();
		this.searchReady = false;
	}

}
